package com.tjetc.service.Impl;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.models.*;
import com.aliyun.sdk.service.dysmsapi20170525.*;
import com.tjetc.common.AliyunSmsInfo;
import com.tjetc.service.AliyunSmsService;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Service
public class AliyunSmsServiceImpl implements AliyunSmsService {

    @Autowired
    private AliyunSmsInfo aliyunSmsInfo;

    /***
     * 注册
     * @param phone
     * @return
     * @throws Exception
     */
    @Override
    public String sendRegister(String phone) throws Exception {
        return send(aliyunSmsInfo.getAccessKeyId(),aliyunSmsInfo.getAccessKeySecret(),aliyunSmsInfo.getSignName(),aliyunSmsInfo.getRegisterTemplateCode(),phone);
    }

    /***
     * 登录
     * @param phone
     * @return
     * @throws Exception
     */
    @Override
    public String sendLogin(String phone) throws  Exception {
        return send(aliyunSmsInfo.getAccessKeyId(),aliyunSmsInfo.getAccessKeySecret(),aliyunSmsInfo.getSignName(),aliyunSmsInfo.getLoginTemplateCode(),phone);
    }

    /***
     * 身份验证
     * @param phone
     * @return
     * @throws Exception
     */
    @Override
    public String identityAuthentication(String phone) throws  Exception {
        return send(aliyunSmsInfo.getAccessKeyId(),aliyunSmsInfo.getAccessKeySecret(),aliyunSmsInfo.getSignName(),aliyunSmsInfo.getIdentityAuthentication(),phone);
    }

    /***
     * 发送短息函数
     * @param key
     * @param keySecret
     * @param signName
     * @param code
     * @param phone
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    private static String send(String key,String keySecret,String signName,String code,String phone) throws ExecutionException, InterruptedException {
        // 设置秘钥
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId(key)
                .accessKeySecret(keySecret)
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .build());

        // 配置发送器
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // 配置短信
        String msgCode=getMsgCode();
        //设置发送短信的信息
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(signName)
                .templateCode(code)
                .phoneNumbers(phone)
                .templateParam("{\"code\":\"" + msgCode + "\"}")
                .build();
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // 关闭发送器
        client.close();
        return msgCode;
    }

    /**
     * 生成随机的4位数，短信验证码
     * @return
     */
    private static String getMsgCode() {
        int n = 4;
        StringBuilder code = new StringBuilder();
        Random ran = new Random();
        for (int i = 0; i < n; i++) {
            code.append(Integer.valueOf(ran.nextInt(10)).toString());
        }
        return code.toString();
    }
}
